package lib.pacificapp.datahub.util.impl;
 

import java.util.Properties;

import lib.pacificapp.datahub.DatahubListener;
import lib.pacificapp.datahub.model.Param;
import lib.pacificapp.model.Kv;
import lib.pacificapp.model.Message;
 

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.util.Log;

public class RequestRunnable implements Runnable {
	 
	private RequestParser mRequestParser;
	public void setRequestParser(RequestParser mParser){
		 mRequestParser=mParser;
	 }
	private Param param = null;
	public void setParam(Param mParam){
		param=mParam;
	}
	private DatahubListener mDatahubListener;   
	public  void setDatahubListener(DatahubListener callBack) {
		mDatahubListener = callBack;
	}
	
   private Context _context;
   @Override
	public void run() {
        if (param == null||_context==null||param.url.equals("")) {
			 throw new IllegalArgumentException("请输入接口地址!");
		 }
        getData();
	}
   
   
	public void setRequest(Context context,Param _param) {
		try{
		_context=context;
		param=_param;  
		if (needSetProxy(context)) {
			Properties prop = System.getProperties();
			prop.put("http.proxyHost", Proxy.getDefaultHost());
			prop.put("http.proxyPort", "" + Proxy.getDefaultPort());
		}
		}
		catch(java.lang.Exception e){
			e.printStackTrace();
		}
	}
	
	 
	protected Message getData(){
		  HttpClient httpClient=null; 
	 	 int code=0;
	 	 
	 	
		  String body  ="";
	     String msg="success";
	     try {
	         httpClient = new HttpClient();
		     PostMethod poster = new PostMethod(param.url);
		     Log.d("post.url", String.valueOf(param.url));
		     int le=param.getJsonString().length();
		     Log.d("post.请求参数",  param.getJsonString());
		     if(param.methodType==Param.METHOD_TYPE_JSON){
		    	 Log.d("post.请求格式", "JSON");
		    	 if(mRequestParser==null){
		    		 poster.setRequestBody(param.getValue());
		    	 }else{
		    		  Log.d("post.请求参数2",mRequestParser.parseParamBody(param.getValue()));
		    		  poster.setRequestBody(mRequestParser.parseParamBody(param.getValue()));
		    	 }
		    	  
		    	  httpClient.executeMethod(poster); 
		    	   body  = poster.getResponseBodyAsString(10000000); 
				    poster.releaseConnection();
		     }
		     if(param.methodType==Param.METHOD_TYPE_DEFAULT){
		    	 Log.d("post.请求格式", "post");
		    	  for(Kv kv:param.value){
		  		    poster.setParameter(kv.getKey(),kv.getString());
		    	 }
		    	  httpClient.executeMethod(poster); 
		    	  body  = poster.getResponseBodyAsString(10000000); 
		    	  
				    poster.releaseConnection();
		     }       
		     if(param.methodType==Param.METHOD_TYPE_GET){
		    	 Log.d("get.请求格式", "get");
		    	 HttpMethodParams p1=new HttpMethodParams();
		    	  StringBuffer q=new StringBuffer("?t=1");
		    	  for(Kv kv:param.value){
		    		   q.append("&");
		    		   q.append(kv.getKey());
		    		   q.append("=");
		    		   q.append(kv.getString()); 
		    	  }
		    	  Log.d("get.QueryString", param.url+ q.toString());
		    	  GetMethod getter=new GetMethod(param.url+q.toString());
		    	  httpClient.executeMethod(getter); 
		    	  
		    	  body  =getter.getResponseBodyAsString(10000000); 
		    	  //Log.d("post.返回",body); 
		    	   getter.releaseConnection();
		     }     
			     if(param.methodType==Param.METHOD_TYPE_DEFAULT)
				           code=poster.getStatusCode();
				    else  code=0;
				   if(mDatahubListener!=null)
				    	 mDatahubListener.onDatahubSuccess(body);
               
		   }catch (Exception e) { 
			     code=-1;
			     
			     msg= e.getMessage();
	             Log.d("post.error",String.valueOf(e.getMessage()));
	               e.printStackTrace();
		   }finally{ 
			  httpClient=null;
			  if(mDatahubListener!=null)
				  mDatahubListener.onDatahubFinish(code, msg);
			 
		 }
	     Message data=new Message();
	     data.setCode(code);
	     data.setMsg(body);
	     return data;
		
		 
	}

	/**
	 * 是否需要使用代理
	 * 
	 * @param context
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("DefaultLocale")
	boolean needSetProxy(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mobNetInfo = connectivityManager.getActiveNetworkInfo();
		if (mobNetInfo == null || "WIFI".equals(mobNetInfo.getTypeName())) {
			return false;
		}
		if (mobNetInfo.getSubtypeName().toLowerCase().contains("cdma")) {
			// 电信网络
			if (android.net.Proxy.getDefaultHost() != null && android.net.Proxy.getDefaultPort() != -1) {
				return true;
			}
		} else if (mobNetInfo.getExtraInfo().contains("wap")) {
			// 移动或联通网络
			return true;
		}
		return false;
	}
}
